package com.hankol.message.imConfig

import android.content.Context
import android.graphics.Color
import android.text.Spannable
import android.text.SpannableString
import android.view.LayoutInflater
import android.view.ViewGroup
import android.widget.ImageView
import com.baselibrary.Constants
import com.baselibrary.bean.IMUserBean
import com.baselibrary.extension.checkNotNull
import com.baselibrary.extension.foregroundColorSpan
import com.baselibrary.extension.load
import com.baselibrary.view.VipHeardImgView
import com.hankol.message.R
import io.rong.imkit.conversation.messgelist.provider.BaseMessageItemProvider
import io.rong.imkit.model.UiMessage
import io.rong.imkit.userinfo.RongUserInfoManager
import io.rong.imkit.widget.adapter.IViewProviderListener
import io.rong.imkit.widget.adapter.ViewHolder
import io.rong.imlib.model.MessageContent
import android.text.Spanned
import android.text.TextUtils
import android.view.View
import android.widget.TextView
import com.baselibrary.bean.LIVE_STATE_END
import com.baselibrary.bean.LIVE_STATE_ING
import com.baselibrary.bean.LIVE_STATE_NO_START
import com.baselibrary.manager.SensorsDataManager
import com.baselibrary.router.ActivityRouter
import com.baselibrary.utils.*
import com.hankol.message.bean.DynamicCardMessage
import com.hankol.message.view.MyImageSpan
import io.rong.imlib.RongIMClient
import io.rong.imlib.model.Message


//动态卡片
class CustomDynamicCardMessageProvider : BaseMessageItemProvider<DynamicCardMessage>() {

    init {
        //修改模板属性
        this.mConfig.showReadState = true //单聊会话中是否在消息旁边显示已读回执状态。
        this.mConfig.showContentBubble = false //是否需要展示气泡

    }

    /**
     * @param holder ViewHolder
     * @param t 自定义消息
     * @param uiMessage {@link UiMessage}
     * @param position 位置
     * @param list 列表数据
     * @param listener ViewModel 的点击事件监听器。如果某个子 view 的点击事件需要 ViewModel 处理，可通过此监听器回调。
     * @return 点击事件是否被消费
     */
    override fun onItemClick(p0: ViewHolder?, p1: DynamicCardMessage?, p2: UiMessage?, p3: Int, p4: MutableList<UiMessage>?, p5: IViewProviderListener<UiMessage>?): Boolean {
        return false
    }

    override fun isMessageViewType(messageContent: MessageContent?): Boolean {
        return messageContent is DynamicCardMessage && !messageContent.isDestruct
    }

    override fun onCreateMessageContentViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {

        val textView = LayoutInflater.from(parent.context).inflate(R.layout.layout_message_dynamic_card, parent, false)

        return ViewHolder(parent.context, textView)
    }

    /**
     * 设置消息视图里各 view 的值
     * @param holder ViewHolder
     * @param parentHolder 父布局的 ViewHolder
     * @param t 此展示模板对应的消息
     * @param uiMessage {@link UiMessage}
     * @param position 消息位置
     * @param list 列表
     * @param listener ViewModel 的点击事件监听器。如果某个子 view 的点击事件需要 ViewModel 处理，可通过此监听器回调。
     */
    override fun bindMessageContentViewHolder(holder: ViewHolder, parentHolder: ViewHolder, message: DynamicCardMessage, uiMessage: UiMessage, position: Int, list: List<UiMessage>, listener: IViewProviderListener<UiMessage>) {
        message.apply {
            //封面
            val imgCover = holder.getView<ImageView>(R.id.img_cover)
            imgCover.load(holder.context, cover)

            //是否显示视频角标
            holder.setVisible(R.id.img_play, type == Constants.DYNAMIC_TYPE_VIDEO)

            //底部头像昵称  话题 直播 文章 隐藏底部
            holder.setVisible(R.id.ll_bottom_img2name, !(type == Constants.DYNAMIC_TYPE_LIVE || type == Constants.DYNAMIC_TYPE_ARTICLE || type == Constants.DYNAMIC_TYPE_TOPIC))
            //底部用户头像
            holder.getView<VipHeardImgView>(R.id.img_heard).setData(heardUrl, isFans == 1)
            //底部昵称
            holder.setText(R.id.tv_auther, nickName)
            holder.itemView.setOnClickListener {
                if (type == Constants.DYNAMIC_TYPE_LIVE) {//直播 todo 更新直播状态
                    val map = HashMap<String, String>()
                    map.put("liveState", LIVE_STATE_END.toString())
                    RongIMClient.getInstance().updateMessageExpansion(map, uiMessage.uId, object : RongIMClient.OperationCallback() {
                        override fun onSuccess() {
                            HKLogUtils.e("===============================更新扩展消息成功")
                        }

                        override fun onError(p0: RongIMClient.ErrorCode?) {
                            HKLogUtils.e("===============================更新扩展消息失败" + p0.toString())
                        }
                    })
                    SensorsDataManager.instance.appFriendsShareClick(title, type)
                    if (path.checkNotNull()) {
                        ARouterUtils.jump(path)
                    } else {
                        //兼容ios发给来的没有带路由，需要自己处理
                        //直播中
                        val hashMap = java.util.HashMap<String, Any>()
                        hashMap["id"] = id
                        ARouterUtils.jump(if (liveState == LIVE_STATE_NO_START) ActivityRouter.ACTIVITY.ACTIVE_LIVE_INFO else ActivityRouter.ACTIVITY.ACTIVE_LIVE_PLAYER, hashMap)
                    }
                } else {
                    SensorsDataManager.instance.appFriendsShareClick(title, type)
                    ARouterUtils.jump(path)
                }
            }
            val tvContent = holder.getView<TextView>(R.id.tv_content)
//            val layoutParams = imgCover.layoutParams
//            layoutParams.height = DensityUtil.dip2px(holder.context, if (type == Constants.DYNAMIC_TYPE_LIVE) 216f else 144f)
//            imgCover.layoutParams = layoutParams
            ImageUtils.setImageViewSize(imgCover, false)
            //直播状态
            holder.setVisible(R.id.ll_live_status, type == Constants.DYNAMIC_TYPE_LIVE)
            if (type == Constants.DYNAMIC_TYPE_LIVE) {
                //直播，
                //获取扩展信息
                if (null != uiMessage.getMessage().getExpansion() && !TextUtils.isEmpty(uiMessage.getMessage().getExpansion().get("liveState")) && uiMessage.getMessage().getExpansion().get("liveState").checkNotNull()) {
                    val liveState = uiMessage.getMessage().getExpansion().get("liveState")
                    holder.setText(R.id.tv_live_status, liveStateShowStr(liveState!!.toInt()))
                            .setVisible(R.id.iv_live_status, liveState!!.toInt() == LIVE_STATE_ING)
                    val imgLiveStatus = holder.getView<ImageView>(R.id.iv_live_status)
                    imgLiveStatus.load(holder.context, R.drawable.ic_msg_live)
                    holder.setVisible(R.id.ll_bottom_all, false)
                    holder.setVisible(R.id.ll_content_live, true)
                    holder.setText(R.id.tv_content_live, title)
                    holder.getView<VipHeardImgView>(R.id.img_heard_live).setData(heardUrl, isFans == 1)
                    holder.setText(R.id.tv_auther_live, nickName)
                }
            } else {
                holder.setVisible(R.id.ll_bottom_all, true)
                holder.setVisible(R.id.ll_content_live, false)
            }
            if (type == Constants.DYNAMIC_TYPE_TOPIC) {
                //话题动态
                val drawable = holder.context.getResources().getDrawable(R.drawable.ic_chat_topic);
                drawable.setBounds(0, 0, 46, 46);
                val spannableString = SpannableString(if (title.startsWith(" # ")) title.substring(" # ".length) else title)
                spannableString.setSpan(MyImageSpan(drawable), 0, 1, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                tvContent.text = spannableString
            } else {
                //标题
                holder.setText(R.id.tv_content, title)
                holder.setVisible(R.id.tv_content, title.checkNotNull())
            }
        }
        //
        //        view.setOnClickListener(object : View.OnClickListener {
        //            override fun onClick(view: View) {
        //                val parent = view.getParent()
        //                if (parent is View) {
        //                    (parent as View).performClick()
        //                }
        //
        //            }
        //        })
        holder.itemView.setOnLongClickListener(object : View.OnLongClickListener {
            override fun onLongClick(view: View): Boolean {
                val parent = view.getParent()
                return if (parent is View) (parent as View).performLongClick() else false
            }
        })
    }

    //直播状态
    private fun liveStateShowStr(liveState: Int): String {
        var str = ""
        when (liveState) {
            LIVE_STATE_NO_START -> {
                str = "未开始"
            }
            LIVE_STATE_ING -> {
                str = "直播中"
            }
            LIVE_STATE_END -> {
                str = "已结束"
            }
        }
        return str
    }

    /**
     * 在会话列表页某条会话最后一条消息为该类型消息时，会话里需要展示的内容。
     * 比如: 图片消息在会话里需要展示为"图片"，那返回对应的字符串资源即可。
     * @param context 上下文
     * @param t 消息内容
     * @return 会话里需要展示的字符串资源
     */
    override fun getSummarySpannable(context: Context, message: DynamicCardMessage): Spannable {
        //1：图片 2：视频 3话题、4文章、 5直播、6 百科  7 讲坛的视频详情
        //        分享[图文动态]、分享[视频动态]、分享[专栏文章]、分享[话题]、分享[直播间]
        var str = "分享[动态]"
        when (message.type) {
            Constants.DYNAMIC_TYPE_IMG -> {
                str = "分享[图文动态]"
            }
            Constants.DYNAMIC_TYPE_VIDEO -> {
                str = "分享[视频动态]"
            }
            Constants.DYNAMIC_TYPE_TOPIC -> {
                str = "分享[话题]"
            }
            Constants.DYNAMIC_TYPE_LIVE -> {
                str = "分享[直播间]"
            }
            Constants.DYNAMIC_TYPE_ARTICLE -> {
                str = "分享[专栏文章]"
            }
            Constants.PRIVATE_MES_TYPE_FOOD_DETAILS -> {
                str = "分享[下酒菜菜谱]"
            }
        }
        return SpannableString(str.foregroundColorSpan(2..str.length, Color.parseColor("#F54D53")))
        /*        var spannableString = SpannableString("分享[动态]")
                spannableString.setSpan(ForegroundColorSpan(Color.parseColor("#F54D53")), 2, 4, 0);
                return spannableString*/

        /*  if (message != null && !TextUtils.isEmpty(message!!.getContent())) {
              var content = message!!.getContent()
              content = content.replace("\n", " ")
              if (content.length > 100) {
                  content = content.substring(0, 100)
              }

              return SpannableString(AndroidEmoji.ensure(content))
          } else {
              return SpannableString("")
          }*/
    }

    override fun bindViewHolder(holder: ViewHolder, uiMessage: UiMessage, position: Int, list: MutableList<UiMessage>, listener: IViewProviderListener<UiMessage>) {
        super.bindViewHolder(holder, uiMessage, position, list, listener)
        holder.setText(R.id.rc_time, TimeUtil.fromToday(uiMessage.sentTime))
        if (uiMessage.senderUserId.checkNotNull() && RongUserInfoManager.getInstance().getUserInfo(uiMessage.senderUserId).checkNotNull() && RongUserInfoManager.getInstance().getUserInfo(uiMessage.senderUserId).extra.checkNotNull()) {
            val isFans = GsonUtils.parseJsonToBean(RongUserInfoManager.getInstance().getUserInfo(uiMessage.senderUserId).extra, IMUserBean::class.java).isFans == 1
            holder.setVisible(R.id.img_vip_tag_right, ("${SpUtils.getInstance().loadUserBean.data.id}").equals(uiMessage.senderUserId) && isFans && (uiMessage.messageDirection == Message.MessageDirection.SEND))
            holder.setVisible(R.id.img_vip_tag_left, (!("${SpUtils.getInstance().loadUserBean.data.id}").equals(uiMessage.senderUserId)) && isFans)
        }
    }
}
